/**
 * AI设置弹窗组件
 * 用于配置AI服务提供商和相关参数
 */

import React, { useState } from 'react'
import { Modal, Form, Input, Slider, InputNumber, Button, message, Radio, AutoComplete, Space, Tooltip } from 'antd'
import { CheckCircleOutlined, LoadingOutlined, SyncOutlined, DollarOutlined } from '@ant-design/icons'
import { AIConfig, saveAIConfig, getAIConfig, getDefaultAIConfig, AI_PROVIDERS, AIProviderType, testAIConnection, getAvailableModels, getUserBalance } from '../../../services/ai'

export interface AISettingsModalProps {
  visible: boolean
  onClose: () => void
}

export const AISettingsModal: React.FC<AISettingsModalProps> = ({ visible, onClose }) => {
  const [form] = Form.useForm()
  const [selectedProvider, setSelectedProvider] = useState<AIProviderType>('OPENAI')
  const [customBaseUrl, setCustomBaseUrl] = useState(false)
  const [isTesting, setIsTesting] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null)
  const [isSyncingModels, setIsSyncingModels] = useState(false)
  const [isCheckingBalance, setIsCheckingBalance] = useState(false)
  const [balanceInfo, setBalanceInfo] = useState<{ balance: string; totalBalance: string } | null>(null)
  const [availableModels, setAvailableModels] = useState<string[]>([])

  // 弹窗打开时加载配置
  React.useEffect(() => {
    if (visible) {
      const config = getAIConfig()
      if (config) {
        form.setFieldsValue(config)
        // 判断是哪个服务提供商
        if (config.apiBaseUrl) {
          const provider = Object.entries(AI_PROVIDERS).find(
            ([_, p]) => p.baseUrl === config.apiBaseUrl
          )
          if (provider) {
            setSelectedProvider(provider[0] as AIProviderType)
          } else {
            setSelectedProvider('CUSTOM')
            setCustomBaseUrl(true)
          }
        }
      } else {
        const defaultConfig = getDefaultAIConfig()
        form.setFieldsValue({
          ...defaultConfig,
          apiKey: '',
          apiBaseUrl: AI_PROVIDERS.OPENAI.baseUrl
        })
      }
    }
  }, [visible, form])

  const handleSave = (values: AIConfig) => {
    try {
      saveAIConfig(values)
      message.success('AI配置已保存')
      onClose()
    } catch (error) {
      message.error('保存配置失败')
      console.error('[AI设置] 保存失败', error)
    }
  }

  const handleCancel = () => {
    form.resetFields()
    setSelectedProvider('OPENAI')
    setCustomBaseUrl(false)
    onClose()
  }

  const handleProviderChange = (provider: AIProviderType) => {
    setSelectedProvider(provider)
    setTestResult(null) // 清除测试结果
    setBalanceInfo(null) // 清除余额信息
    setAvailableModels([]) // 清除已同步的模型
    const providerInfo = AI_PROVIDERS[provider]

    if (provider === 'CUSTOM') {
      setCustomBaseUrl(true)
      form.setFieldsValue({
        apiBaseUrl: '',
        model: ''
      })
    } else {
      setCustomBaseUrl(false)
      form.setFieldsValue({
        apiBaseUrl: providerInfo.baseUrl,
        model: providerInfo.models[0]
      })
    }
  }

  const handleSyncModels = async () => {
    try {
      // 验证API密钥和端点
      await form.validateFields(['apiKey', 'apiBaseUrl'])

      const values = form.getFieldsValue()
      setIsSyncingModels(true)

      console.log('[AI设置] 同步模型列表')

      const result = await getAvailableModels({
        apiKey: values.apiKey,
        apiBaseUrl: values.apiBaseUrl
      })

      if (result.ok) {
        const modelIds = result.data.map((m: { id: string }) => m.id)
        setAvailableModels(modelIds)
        message.success(`成功获取 ${modelIds.length} 个可用模型`)
        console.log('[AI设置] 获取到模型:', modelIds)
      } else {
        message.error(`获取模型失败: ${result.error.message}`)
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写API密钥和端点地址')
      } else {
        message.error('同步模型失败')
      }
    } finally {
      setIsSyncingModels(false)
    }
  }

  const handleCheckBalance = async () => {
    try {
      // 验证API密钥和端点
      await form.validateFields(['apiKey', 'apiBaseUrl'])

      const values = form.getFieldsValue()
      setIsCheckingBalance(true)
      setBalanceInfo(null)

      console.log('[AI设置] 查询余额', {
        apiKey: values.apiKey?.substring(0, 10) + '...',
        apiBaseUrl: values.apiBaseUrl,
        allValues: values
      })

      const result = await getUserBalance({
        apiKey: values.apiKey,
        apiBaseUrl: values.apiBaseUrl
      })

      if (result.ok) {
        setBalanceInfo(result.data)
        message.success('余额查询成功')
      } else {
        message.error(`余额查询失败: ${result.error.message}`)
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写API密钥和端点地址')
      } else {
        message.error('查询余额失败')
      }
    } finally {
      setIsCheckingBalance(false)
    }
  }

  const handleTestConnection = async () => {
    try {
      // 先验证表单
      await form.validateFields(['apiKey', 'apiBaseUrl', 'model'])

      const values = form.getFieldsValue()
      setIsTesting(true)
      setTestResult(null)

      console.log('[AI设置] 开始测试连接', values)

      const result = await testAIConnection({
        apiKey: values.apiKey,
        apiBaseUrl: values.apiBaseUrl,
        model: values.model,
        temperature: values.temperature || 0.7,
        maxTokens: values.maxTokens || 500
      })

      if (result.ok) {
        setTestResult({
          success: true,
          message: `连接成功！使用模型: ${result.data.model}`
        })
        message.success('连接测试成功')
      } else {
        setTestResult({
          success: false,
          message: result.error.message
        })
        message.error(`连接失败: ${result.error.message}`)
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写必填字段')
      } else {
        setTestResult({
          success: false,
          message: '测试过程出现异常'
        })
        message.error('测试失败')
      }
    } finally {
      setIsTesting(false)
    }
  }

  return (
    <Modal
      title="AI设置"
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={500}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSave}
      >
        <Form.Item label="AI服务提供商">
          <Radio.Group
            value={selectedProvider}
            onChange={(e) => handleProviderChange(e.target.value)}
            style={{ width: '100%' }}
          >
            <Radio.Button value="OPENAI" style={{ width: '33%', textAlign: 'center' }}>
              OpenAI
            </Radio.Button>
            <Radio.Button value="SILICONFLOW" style={{ width: '34%', textAlign: 'center' }}>
              硅基流动
            </Radio.Button>
            <Radio.Button value="CUSTOM" style={{ width: '33%', textAlign: 'center' }}>
              自定义
            </Radio.Button>
          </Radio.Group>
        </Form.Item>

        {/* apiBaseUrl字段 - 自定义时显示,其他情况隐藏但保留值 */}
        <Form.Item
          label={customBaseUrl ? "API端点地址" : undefined}
          name="apiBaseUrl"
          rules={customBaseUrl ? [{ required: true, message: '请输入API端点地址' }] : []}
          extra={customBaseUrl ? "兼容OpenAI格式的API地址，例如：https://api.example.com/v1" : undefined}
          hidden={!customBaseUrl}
        >
          {customBaseUrl ? (
            <Input placeholder="https://api.example.com/v1" />
          ) : (
            <Input type="hidden" />
          )}
        </Form.Item>

        <Form.Item
          label="API密钥"
          name="apiKey"
          rules={[{ required: true, message: '请输入API密钥' }]}
          extra={
            selectedProvider === 'OPENAI'
              ? '请输入您的OpenAI API密钥，格式为 sk-...'
              : selectedProvider === 'SILICONFLOW'
              ? '请输入您的SiliconFlow API密钥'
              : '请输入API密钥'
          }
        >
          <Input.Password
            placeholder={selectedProvider === 'OPENAI' ? 'sk-...' : 'API密钥'}
            autoComplete="off"
          />
        </Form.Item>

        <Form.Item
          label={
            <Space>
              <span>AI模型</span>
              <Tooltip title="点击同步按钮从服务商获取最新可用模型列表">
                <Button
                  size="small"
                  type="text"
                  icon={<SyncOutlined spin={isSyncingModels} />}
                  onClick={handleSyncModels}
                  loading={isSyncingModels}
                >
                  {isSyncingModels ? '同步中' : '同步模型'}
                </Button>
              </Tooltip>
            </Space>
          }
          name="model"
          rules={[{ required: true, message: '请输入或选择模型' }]}
          extra={
            selectedProvider === 'SILICONFLOW'
              ? '推荐使用Qwen2.5-7B，性能优秀且完全免费。可从列表选择或手动输入'
              : selectedProvider === 'OPENAI'
              ? 'GPT-4质量更高但成本较高，GPT-3.5性价比更好。可从列表选择或手动输入'
              : '请输入模型名称'
          }
        >
          {customBaseUrl ? (
            <AutoComplete
              options={availableModels.map((model) => ({
                value: model,
                label: model
              }))}
              placeholder="请输入模型名称或点击上方【同步模型】按钮获取"
              filterOption={(inputValue, option) =>
                option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
              }
            />
          ) : (
            <AutoComplete
              options={[
                ...AI_PROVIDERS[selectedProvider].models,
                ...availableModels
              ].filter((v, i, a) => a.indexOf(v) === i).map((model) => ({
                value: model,
                label: model
              }))}
              placeholder="请选择或输入模型名称"
              filterOption={(inputValue, option) =>
                option!.value.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
              }
            />
          )}
        </Form.Item>

        <Form.Item
          label="创造性 (Temperature)"
          name="temperature"
          extra="0为保守，1为创造性，建议范围0.5-0.8"
        >
          <Slider
            min={0}
            max={1}
            step={0.1}
            marks={{
              0: '保守',
              0.5: '平衡',
              1: '创造'
            }}
          />
        </Form.Item>

        <Form.Item
          label="最大输出长度 (Tokens)"
          name="maxTokens"
          extra="控制AI单次生成的最大长度，1 token ≈ 0.75个汉字"
        >
          <InputNumber
            min={100}
            max={2000}
            step={100}
            style={{ width: '100%' }}
          />
        </Form.Item>

        <Form.Item style={{ marginBottom: 0, marginTop: 24 }}>
          <Space direction="vertical" style={{ width: '100%' }} size="middle">
            {/* 测试连接和查询余额按钮 */}
            <Space style={{ width: '100%' }}>
              <Button
                style={{ flex: 1 }}
                onClick={handleTestConnection}
                loading={isTesting}
                icon={isTesting ? <LoadingOutlined /> : <CheckCircleOutlined />}
              >
                {isTesting ? '测试中...' : '测试连接'}
              </Button>
              {selectedProvider === 'SILICONFLOW' && (
                <Tooltip title="查询硅基流动账户余额">
                  <Button
                    onClick={handleCheckBalance}
                    loading={isCheckingBalance}
                    icon={<DollarOutlined />}
                  >
                    {isCheckingBalance ? '查询中' : '查询余额'}
                  </Button>
                </Tooltip>
              )}
            </Space>

            {/* 测试结果 */}
            {testResult && (
              <div style={{
                padding: '8px 12px',
                borderRadius: 4,
                backgroundColor: testResult.success ? '#f6ffed' : '#fff2e8',
                border: `1px solid ${testResult.success ? '#b7eb8f' : '#ffbb96'}`,
                color: testResult.success ? '#52c41a' : '#fa8c16'
              }}>
                {testResult.message}
              </div>
            )}

            {/* 余额信息 */}
            {balanceInfo && (
              <div style={{
                padding: '8px 12px',
                borderRadius: 4,
                backgroundColor: '#e6f7ff',
                border: '1px solid #91d5ff',
                color: '#0050b3'
              }}>
                <div>当前余额: {balanceInfo.balance}</div>
                <div>总余额: {balanceInfo.totalBalance}</div>
              </div>
            )}

            {/* 保存和取消按钮 */}
            <div style={{ display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>
              <Button onClick={handleCancel}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                保存配置
              </Button>
            </div>
          </Space>
        </Form.Item>
      </Form>

      <div style={{ marginTop: 16, padding: 12, background: '#f5f5f5', borderRadius: 4, fontSize: 12 }}>
        <strong>注意事项：</strong>
        <ul style={{ margin: '8px 0 0 0', paddingLeft: 20 }}>
          <li>API密钥会加密存储在本地，不会上传到服务器</li>
          <li>请妥善保管您的API密钥，不要分享给他人</li>
          <li>使用AI功能会消耗相应服务商的账户余额</li>
          {selectedProvider === 'SILICONFLOW' && (
            <li style={{ color: '#52c41a', fontWeight: 'bold' }}>
              硅基流动提供免费额度，适合个人用户测试使用
            </li>
          )}
        </ul>
      </div>
    </Modal>
  )
}
